<template>
  <view class="voting-results-container">
    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-input-wrapper" @click="openHouseModal">
        <u-search
          v-model="searchKeyword"
          placeholder="请选择"
          :showAction="false"
          :clearabled="false"
          :disabled="true"
          readonly
        />
        <view class="search-icon">
          <u-icon name="search" size="20" color="#999"></u-icon>
        </view>
      </view>
      <!-- 清除搜索按钮 -->
      <view v-if="searchKeyword" class="clear-search" @click="clearSearch">
        <u-icon name="close" size="16" color="#999"></u-icon>
        <text class="clear-text">清除</text>
      </view>
    </view>
    
    <!-- 列表内容 -->
    <view class="list-container">
      <block v-if="list.length>0">
        <view 
          v-for="(item, index) in list" 
          :key="index" 
          class="list-item"
        > 
        <!-- <view class="room-info">{{ item.roomCode || '未知房间' }}</view> -->
          <view class="item-header">
            <view class="user-info">
              <!-- <Tag size="25rpx" :text="item.voteOption" type="notstart" /> -->
              <view class="name">{{ item.voteName || '匿名用户' }}({{  formatMobile(item.mobile) }})</view>

            </view>
           
          </view>
          
          <view class="item-content">
               <view class="vote-time vote-house-wrapper">
                <text class="label">投票住宅：</text>
                <view class="value house-value-column">
                  <!-- 第一个房屋 -->
                  <view style="position: relative;left: -15px;" v-if="item.houseDtos && item.houseDtos.length > 0" class="house-row">
                    {{ formatSingleHouse(item.houseDtos[0]) }}
                  </view>
                  <!-- 第二个房屋 + 展开图标 -->
                  <view v-if="item.houseDtos && item.houseDtos.length > 1" class="house-row house-row-with-icon">
                    <text>{{ formatSingleHouse(item.houseDtos[1]) }}</text>
                    <u-icon 
                      v-if="item.houseDtos.length > 2" 
                      @click="handleShowHouses(item)" 
                      name="arrow-right" 
                      size="16" 
                      color="#666"
                      style="margin-left: 8rpx;"
                    ></u-icon>
                  </view>
                </view>
            </view>
            
            <view class="vote-time">
              <text class="label">投票时间：</text>
              <text class="value">{{ formatDate(item.createDate) }}</text>
            </view>
            <view class="vote-time" :class="item.voteOption.length<=1?'': 'u-col-top'" >
              <text class="label">投票选项</text>
              <view class="value value-flex">
              <view :class="item.voteOption.length<=1?'': 'u-m-b-10'" v-for="(option,index) in item.voteOption" :key="index">{{ option }}</view>
            </view>
            </view>
          </view>
        </view>
        
        <!-- 加载更多 -->
        <u-loadmore 
          :status="loadMoreStatus" 
          :loading-text="loadingText"
          :loadmore-text="loadmoreText"
          :nomore-text="nomoreText"
          @loadmore="loadMore"
        />
      </block>
      
      <!-- 空状态 -->
      <view v-if="list.length === 0 && !loading" class="empty-state">
         <u-empty text="暂无投票记录" />
      </view>
    </view>
    
    <!-- 房屋选择弹窗 -->
    <ChooseBuildingModel 
    v-if="communityId>0"
      v-model="showHouseModal" 
      @confirm="handleHouseConfirm"
      :communityId="communityId" 
      :singleSelect="true"
    />
    
    <!-- 房屋列表弹窗 -->
    <u-popup  :show="showHouseListModal" 
    @close="handleCancel"
    mode="center" border-radius="20" closeable>
     <!-- <view>111</view> -->
      <view class="house-list-modal">
        <view class="modal-title">投票住宅列表</view>
        <view class="modal-content">
          <view 
            v-for="(house, index) in currentHouses" 
            :key="index"
            class="house-item-modal"
          >
            <text class="house-name">{{ house.name }}</text>
            <text class="house-area">({{ house.area }}m²)</text>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getRecordList,queryRecord } from '@/api'
import Tag from '@/components/tag/index.vue'
import ChooseBuildingModel from '@/components/ChooseBuildingModel/index.vue'
import { mapState } from 'vuex'

export default {
  components:{
    Tag,
    ChooseBuildingModel
  },
  data() {
    return {
      list: [],
      hasMore: true,
      loading: false,
      voteId: 0,
      communityId: 0,
      searchKeyword: '', // 搜索关键词
      showHouseModal: false, // 房屋选择弹窗
      selectedHouse: null, // 选中的房屋
      showHouseListModal: false, // 房屋列表弹窗
      currentHouses: [], // 当前查看的房屋列表
      // 搜索条件
      query: {
        communityId: '',
        areaId: '',
        buildId: '',
        unitId: '',
        pageNum: 1,
        pageSize: 10
      },
      // LoadMore组件相关
      loadMoreStatus: 'loadmore', // loadmore, loading, nomore
      loadingText: '正在加载...',
      loadmoreText: '上拉或点击加载更多',
      nomoreText: '没有更多数据了'
    }
  },
  
  computed: {
    // ...mapState("community", ["communityId"])
  },
  
  onLoad(options) {
    // 从页面参数获取投票ID和社区ID
    if (options.voteId) {
      this.voteId = options.voteId
    }
    if (options.communityId) {
      this.communityId = options.communityId
      this.query.communityId = options.communityId
    }
    this.init()
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    // 重置页码为第一页
    this.query.pageNum = 1
    this.refresh()
  },
  
  // 上拉加载更多
  onReachBottom() {
    if (this.loadMoreStatus === 'loadmore' && !this.loading) {
      this.loadMore()
    }
  },
  
  methods: {
    handleCancel(){
     
      this.showHouseListModal = false
      console.log("我触发了",this)
    },
    // 打开房屋选择弹窗
    openHouseModal() {
      this.showHouseModal = true
    },
    
    // 清除搜索条件
    clearSearch() {
      this.selectedHouse = null
      this.searchKeyword = ''
      this.query.areaId = ''
      this.query.buildId = ''
      this.query.unitId = ''
      this.query.pageNum = 1
      this.refresh()
    },
    
    // 处理房屋选择确认
    handleHouseConfirm(selectedHouses) {
      console.log("我触发了handleHouseConfirm",selectedHouses)

      if (selectedHouses && selectedHouses.length > 0) {
        // 取第一个选中的房屋
        const house = selectedHouses[0]
        this.selectedHouse = house
        
        // 设置搜索条件到query中
        this.query.areaId = house.areaId || ''
        this.query.buildId = house.buildingId || ''
        this.query.unitId = house.unitId || ''
        
        // 设置搜索关键词为房屋信息
        this.searchKeyword = `${house.areaName}${house.buildingName}${house.unitName}`
        
        // 执行搜索
        this.query.pageNum = 1
        this.refresh()
      }
    },
    
    // 统一的数据获取方法
    async fetchData(isLoadMore = false) {
      const params = {
        voteId: this.voteId,
        // 将搜索条件合并到请求参数中
        ...this.query,
        recordStatus:1
      }
      
      // 如果是加载更多，增加页码
      if (isLoadMore) {
        params.pageNum = this.query.pageNum + 1
      }
      
      try {
        const res = await queryRecord(params)
        
        // 处理数据
        const processedList = (res.rows || []).map(item => {
          if(item.roomCode){
            item.roomCode = item.roomCode.split('#').join('-')
          }
          try {
            item.voteOption = (JSON.parse(item.voteOption))
          } catch (error) {
            item.voteOption = []
          }
        
          return item
        })
        
        if (isLoadMore) {
          // 加载更多模式
          if (processedList.length > 0) {
            this.list = [...this.list, ...processedList]
            this.query.pageNum++
            this.hasMore = processedList.length >= this.query.pageSize
            this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore'
          } else {
            this.hasMore = false
            this.loadMoreStatus = 'nomore'
          }
        } else {
          // 初始化模式
          this.list = processedList
          this.totalCount = res.total || 0
          this.hasMore = processedList.length >= this.query.pageSize
          this.loadMoreStatus = this.hasMore ? 'loadmore' : 'nomore'
        
          
          // 停止下拉刷新
          uni.stopPullDownRefresh()
        }
        
        return res
      } catch (error) {
        const errorMsg = isLoadMore ? '加载更多失败' : '获取投票记录失败'
        console.error(errorMsg + ':', error)
        uni.$u.toast(errorMsg)
        this.loadMoreStatus = 'loadmore'
        throw error
      }
    },
    
    async init() {
      this.loading = true
      this.loadMoreStatus = 'loading'
      try {
        await this.fetchData(false)
      } finally {
        this.loading = false
      }
    },
    
    async loadMore() {
      if (this.loading || this.loadMoreStatus !== 'loadmore') return
      
      this.loading = true
      this.loadMoreStatus = 'loading'
      try {
        await this.fetchData(true)
      } finally {
        this.loading = false
      }
    },
    
    async refresh() {
      // 确保pageNum重置为第一页
      this.query.pageNum = 1
      this.hasMore = true
      this.loadMoreStatus = 'loadmore'
      this.list = []
      await this.init()
    },
    
    // 格式化手机号（隐藏中间4位）
    formatMobile(mobile) {
      if (!mobile) return '未知'
      if (mobile.length === 11) {
        return mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      return mobile
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间'
      
      const date = new Date(dateStr)
      if (isNaN(date.getTime())) return '未知时间'
      
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hour = String(date.getHours()).padStart(2, '0')
      const minute = String(date.getMinutes()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    
    // 格式化单个房屋名称
    formatSingleHouse(house) {
      if (!house) return '未知'
      const areaInfo = house.areaInfo ? house.areaInfo.replace(/#/g, '-') : ''
      return areaInfo + '-' + (house.roomCode || house.pmsHouse?.roomCode || '')
    },
    
    // 格式化房屋名称
    formatHouseName(houseDtos) {
      if (!houseDtos || houseDtos.length === 0) return '未知'
      
      // 如果只有1-2个房屋，直接显示全部
      if (houseDtos.length <= 2) {
        return houseDtos.map(house => {
          const areaInfo = house.areaInfo ? house.areaInfo.replace(/#/g, '-') : ''
          return areaInfo + '-' + (house.roomCode || house.pmsHouse?.roomCode || '')
        }).join('、')
      }
      
      // 超过2个，只显示前2个
      const displayHouses = houseDtos.slice(0, 2).map(house => {
        const areaInfo = house.areaInfo ? house.areaInfo.replace(/#/g, '-') : ''
        return areaInfo + '-' + (house.roomCode || house.pmsHouse?.roomCode || '')
      }).join('、')
      
      return displayHouses
    },
    
    // 显示房屋列表弹窗
    handleShowHouses(item) {
    
      if (!item.houseDtos || item.houseDtos.length <= 2) return
     
      this.currentHouses = item.houseDtos.map(house => {
        const areaInfo = house.areaInfo ? house.areaInfo.replace(/#/g, '-') : ''
        const roomCode = house.roomCode || house.pmsHouse?.roomCode || ''
        const houseSize = house.pmsHouse?.houseSize || house.houseSize || 0
        return {
          name: areaInfo + '-' + roomCode,
          area: houseSize
        }
      })
      console.log("222", this.currentHouses )
      this.showHouseListModal = true
    },
    
    // 关闭房屋列表弹窗
    closeHouseListModal() {
      this.showHouseListModal = false
      this.currentHouses = []
    }
  }
}
</script>

<style lang="scss" scoped>
.voting-results-container {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 24rpx;
}

.search-container {
  margin-bottom: 24rpx;
  
  .search-input-wrapper {
    position: relative;
    
    .search-icon {
      position: absolute;
      right: 20rpx;
      top: 50%;
      transform: translateY(-50%);
      z-index: 10;
    }
  }
  
  .clear-search {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16rpx;
    padding: 12rpx 24rpx;
    background: #f2f2f2;
    border-radius: 8rpx;
    width: -webkit-fit-content;
    width: fit-content;
    position: absolute;
    right: 14px;
    top: 14rpx;
    z-index: 10000;
    
    .clear-text {
      font-size: 24rpx;
      color: #999;
      margin-left: 8rpx;
    }
  }
}

.list-container {
  .list-item {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0rpx 0rpx 27rpx 0rpx rgba(0,0,0,0.03);
    
    .item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;
      
      .user-info {
        width: 100%;
        display: flex;
        align-items: center;
        gap: 10rpx;
        border-bottom: 1px solid #f5f7fa;
        padding-bottom: 20rpx;
        .name {
          font-size: 32rpx;
          font-weight: 600;
          color: #222;
          margin-left: 10rpx;
        }
        
        .mobile {
          font-size: 26rpx;
          color: #666;
        }
      }
      
   
    }
       .room-info {
        font-size: 28rpx;
        color: #4d7cff;
        background: rgba(77, 124, 255, 0.1);
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
      }
    
    .item-content {
      width: 100%;
  
      .vote-option,
      .vote-time {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        justify-content: space-between;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 28rpx;
          color: #666;
          min-width: 140rpx;
        }
        
        .value {
          font-size: 28rpx;
          color: #222;
    
        }
      }
      
      .vote-option .value {
        color: #4d7cff;
        font-weight: 500;
      }
    }
  }
}



.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  
  .empty-icon {
    font-size: 80rpx;
    margin-bottom: 24rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}
.value-flex{
  display: flex;
  flex-direction: column;

}

.house-value {
  display: flex;
  align-items: center;
  gap: 8rpx;
  cursor: pointer;
}

// 房屋列显示样式
.vote-house-wrapper {
  align-items: flex-start !important;
}

.house-value-column {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
  flex: 1;
  
  .house-row {
    font-size: 28rpx;
    color: #666666;
    text-align: right;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .house-row-with-icon {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

// 房屋列表弹窗样式
.house-list-modal {
  padding: 40rpx 32rpx 60rpx;
  max-height: 80vh;
  
  .modal-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #222;
    margin-bottom: 32rpx;
    text-align: center;
  }
  
  .modal-content {
    max-height: 60vh;
    overflow-y: auto;
    
    .house-item-modal {
      display: flex;
      align-items: center;
      padding: 28rpx 30rpx;
      margin-bottom: 16rpx;
      background: #F8F9FA;
      border-radius: 12rpx;
      border: 2rpx solid #E8E9EB;
      
      .house-name {
        font-size: 28rpx;
        color: #333333;
        margin-right: 8rpx;
      }
      
      .house-area {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }
}
</style>